**題號:86 標題:Partition List 難度:Medium
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
我的程式碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null){
return head;
}
ListNode temps = new ListNode(); //previous small
ListNode tempeb = new ListNode(); //previous equal big
ListNode small = new ListNode(); // str small
ListNode eqbi = new ListNode(); // str equal big
ListNode Node_index = new ListNode(); //str
ListNode ebst = new ListNode(-101); //head equal big
ListNode sst = new ListNode(-101);//head small
//root = head;
Node_index = head;
int chs=0,cheb=0;
while(Node_index != null){
if(Node_index.val<x){
if(chs == 0 ){
small = Node_index;
sst =small;
temps = sst;
System.out.println("small: "+ Node_index.val);
Node_index = Node_index.next;
chs++;
}else{
temps.next = Node_index;
small = small.next;
temps = small;
System.out.println("small: "+ Node_index.val);
Node_index = Node_index.next;
}
}else{
if(cheb == 0 ){
eqbi = Node_index;
ebst = eqbi;
tempeb = ebst;
cheb++;
System.out.println("eqbi: "+ Node_index.val);
Node_index = Node_index.next;
}else{
tempeb.next = Node_index;
eqbi = eqbi.next;
tempeb = eqbi;
System.out.println("eqbi: "+ Node_index.val);
Node_index = Node_index.next;
}
}
}
eqbi.next = null;
small.next = null;
// while(ebst != null){
// System.out.println("ebst: "+ ebst.val);
// ebst = ebst.next;
// }
// while(sst != null){
// System.out.println("sst: "+ sst.val);
// sst = sst.next;
// }
if(sst.val == -101){
return ebst;
}else if(ebst.val == -101){
return sst;
}else{
temps.next = ebst;
return sst;
}
}
}
DAY19心得
心態炸裂,不想打字